package com.dm.voicesubtitle.gui;

import com.dm.voicesubtitle.audio.AudioCapture;
import com.dm.voicesubtitle.config.AppConfig;
import com.dm.voicesubtitle.speech.SpeechRecognizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sound.sampled.AudioFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 字幕显示窗口
 */
public class SubtitleWindow extends JFrame {
    private static final Logger logger = LoggerFactory.getLogger(SubtitleWindow.class);
    
    private final SubtitlePanel subtitlePanel;
    private final ControlPanel controlPanel;
    private final AudioCapture audioCapture;
    private final SpeechRecognizer speechRecognizer;
    private final ExecutorService executorService;
    
    public SubtitleWindow() {
        super("实时语音弹幕系统");
        
        // 初始化组件
        this.subtitlePanel = new SubtitlePanel();
        this.controlPanel = new ControlPanel();
        this.executorService = Executors.newFixedThreadPool(4);
        
        // 初始化音频捕获
        this.audioCapture = new AudioCapture(new AudioCapture.AudioDataListener() {
            @Override
            public void onAudioData(byte[] audioData, AudioFormat format) {
                SubtitleWindow.this.onAudioData(audioData, format);
            }
        });
        
        // 初始化语音识别
        this.speechRecognizer = new SpeechRecognizer(new SpeechRecognizer.SpeechRecognitionListener() {
            @Override
            public void onRecognitionResult(SpeechRecognizer.RecognitionResult result) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        subtitlePanel.addSubtitle(result.getTranscript(), result.getLanguageCode());
                    }
                });
            }
            
            @Override
            public void onError(Throwable error) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        JOptionPane.showMessageDialog(SubtitleWindow.this,
                                "语音识别错误: " + error.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                    }
                });
            }
        });
        
        initializeUI();
        setupEventHandlers();
    }
    
    /**
     * 初始化UI界面
     */
    private void initializeUI() {
        AppConfig.DisplayConfig config = AppConfig.getInstance().getDisplayConfig();
        
        setSize(config.getWindowWidth(), config.getWindowHeight());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 设置窗口透明度
        setOpacity(0.8f);
        
        // 设置窗口始终置顶
        setAlwaysOnTop(true);
        
        // 创建主布局
        setLayout(new BorderLayout());
        
        // 添加字幕面板
        add(subtitlePanel, BorderLayout.CENTER);
        
        // 添加控制面板
        add(controlPanel, BorderLayout.SOUTH);
        
        // 设置窗口图标
        try {
            setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icon.png")));
        } catch (Exception e) {
            logger.warn("无法加载窗口图标", e);
        }
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 控制面板事件
        controlPanel.addStartButtonListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                startRecognition();
            }
        });
        controlPanel.addStopButtonListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopRecognition();
            }
        });
        controlPanel.addLanguageChangeListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedLanguage = controlPanel.getSelectedLanguage();
                speechRecognizer.setLanguage(selectedLanguage);
            }
        });
        
        // 窗口关闭事件
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent e) {
                cleanup();
            }
        });
    }
    
    /**
     * 开始语音识别
     */
    private void startRecognition() {
        try {
            audioCapture.startRecording();
            controlPanel.setRecordingState(true);
            logger.info("开始语音识别");
        } catch (Exception e) {
            logger.error("启动语音识别失败", e);
            JOptionPane.showMessageDialog(this,
                    "启动语音识别失败: " + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 停止语音识别
     */
    private void stopRecognition() {
        try {
            audioCapture.stopRecording();
            controlPanel.setRecordingState(false);
            logger.info("停止语音识别");
        } catch (Exception e) {
            logger.error("停止语音识别失败", e);
        }
    }
    
    /**
     * 音频数据回调
     */
    private void onAudioData(byte[] audioData, AudioFormat format) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    // 直接调用语音识别，不使用CompletableFuture的高级特性
                    Thread recognitionThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                SpeechRecognizer.RecognitionResult result =
                                    speechRecognizer.recognizeAudioSync(audioData, format);
                                
                                if (result != null) {
                                    SwingUtilities.invokeLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            subtitlePanel.addSubtitle(result.getTranscript(), result.getLanguageCode());
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                logger.error("语音识别处理失败", e);
                            }
                        }
                    });
                    recognitionThread.start();
                } catch (Exception e) {
                    logger.error("处理音频数据失败", e);
                }
            }
        });
    }
    
    /**
     * 清理资源
     */
    private void cleanup() {
        try {
            if (audioCapture.isRecording()) {
                audioCapture.stopRecording();
            }
            
            if (speechRecognizer != null) {
                speechRecognizer.close();
            }
            
            if (executorService != null) {
                executorService.shutdown();
            }
            
            logger.info("资源清理完成");
        } catch (Exception e) {
            logger.error("清理资源时发生错误", e);
        }
    }
    
    /**
     * 获取字幕面板（用于外部访问）
     */
    public SubtitlePanel getSubtitlePanel() {
        return subtitlePanel;
    }
    
    /**
     * 获取控制面板（用于外部访问）
     */
    public ControlPanel getControlPanel() {
        return controlPanel;
    }
} 